//
//  KLRechargeViewController.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 16/6/29.
//  Copyright © 2016年 陈宾鹏. All rights reserved.
//

#import "KLRechargeViewController.h"
#import "KLHttpAPI.h"
#import "KLHelp.h"
#import "Masonry.h"
#import "BeeCloud+Utils.h"
#import "HemaConst.h"
#import "TSCurrencyTextField.h"
#import "JRToast.h"
#import "MZLoadingCircle.h"

@interface KLRechargeViewController ()<BeeCloudDelegate,UITextFieldDelegate>
{
    UIView *fatherView_1;
    
    UIButton *nextBtn;
    TSCurrencyTextField *numberTF;
    
    MZLoadingCircle *loadingCircle;
}


@property(nonatomic,strong) NSMutableString *money;
@property(nonatomic,strong) NSString *trade_no;
@end

@implementation KLRechargeViewController
-(NSMutableString *)money{
    if(!_money){
        _money = [[NSMutableString alloc]init];
    }
    
    return _money;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"充值";
    //初始化导航栏
    [self naveSet];
    //初始化主界面
    [self uiSet];
    //设置支付代理
    [BeeCloud setBeeCloudDelegate:self];
}

#pragma mark - 初始化导航栏
-(void)naveSet{
    self.navigationController.navigationBarHidden = NO;
    [KLHelp navSet:self doBackHandeler:^(UIButton *backButton) {
        [backButton addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    }];
}-(void)doBack:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 初始化主界面
-(void)uiSet{
    [self setFatherView];
    
    //金额提示label
    UILabel *numberLabel = [[UILabel alloc]init];
    numberLabel.text = @"金额";
    numberLabel.font = [UIFont systemFontOfSize:18.0f];
    [fatherView_1 addSubview:numberLabel];
    [numberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.height.mas_equalTo(40);
        make.centerY.equalTo(fatherView_1).with.offset(0);
    }];
    //输入金额的textfield
    numberTF = [[TSCurrencyTextField alloc]init];
    [numberTF addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    numberTF.borderStyle = UITextBorderStyleNone;
    numberTF.amount = @0.00;
    numberTF.keyboardType = UIKeyboardTypeNumberPad;
    [numberTF becomeFirstResponder];
    [fatherView_1 addSubview:numberTF];
    [numberTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(numberLabel).with.offset(60);
        make.height.mas_equalTo(40);
        make.centerY.equalTo(fatherView_1).with.offset(0);
        make.right.equalTo(fatherView_1).with.offset(-50);
    }];
    //支付宝图标
    UIImageView *aliImage = [[UIImageView alloc]init];
    aliImage.image = [UIImage imageNamed:@"支付宝"];
    aliImage.layer.masksToBounds = YES;
    aliImage.layer.cornerRadius = 5;
    [fatherView_1 addSubview:aliImage];
    [aliImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(35);
        make.width.mas_equalTo(35);
        make.right.mas_equalTo(-5);
        make.centerY.equalTo(fatherView_1).with.offset(0);
    }];
}

-(void)setFatherView{
    self.view.backgroundColor = RGB_UI_COLOR(238, 238, 238);
    UILabel *noticeLabel = [[UILabel alloc]init];
    noticeLabel.text = @"当前仅支持支付宝充值:";
    noticeLabel.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:noticeLabel];
    [noticeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.top.mas_equalTo(0);
        make.height.mas_equalTo(30);
    }];
    
    fatherView_1 = [[UIView alloc]init];
    fatherView_1.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:fatherView_1];
    [fatherView_1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(30);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(50);
    }];
    
    nextBtn = [[UIButton alloc]init];
    [nextBtn setBackgroundColor:RGB_UI_COLOR(170, 170, 170)];
    [nextBtn setEnabled:NO];
    nextBtn.layer.masksToBounds = YES;
    nextBtn.layer.cornerRadius = 5.0f;
    [nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
    [nextBtn addTarget:self action:@selector(rechargeNext:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:nextBtn];
    [nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(fatherView_1).offset(75);
        make.height.mas_equalTo(50);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
    }];
    
    UILabel *tipsLabel = [[UILabel alloc]init];
    tipsLabel.text = @"每次限额1000.00元人民币整！";
    tipsLabel.textColor = RGB_UI_COLOR(255, 153, 0);
    tipsLabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:tipsLabel];
    [tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(nextBtn).offset(70);
        make.centerX.equalTo(self.view).with.offset(0);
    }];
}

#pragma mark - 下一步点击事件
-(void)rechargeNext:(id)sender{
    [self.view endEditing:YES];
    [self showLoadingMode];
    
    //本机当前时间(用于自定义单号)
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYYMMddHHmmss"];
    NSString *locationString=[dateformatter stringFromDate:senddate];
    
    //支付请求
    [BeeCloud initWithAppID:@"1e70e317-1286-490b-ad3b-3d56f8f2e0a0" andAppSecret:@"caf7da3a-1b60-499c-920c-5d0c2008693a"];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:self.money,[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"], nil];
    /**
     按住键盘上的option键，点击参数名称，可以查看参数说明
     **/
    BCPayReq *payReq = [[BCPayReq alloc] init];
    payReq.channel = PayChannelAliApp; //支付渠道
    payReq.title = @"KISSLOCK蓝牙锁充值";//订单标题
    payReq.totalFee = [NSString stringWithFormat:@"%@",self.money];//订单价格
    self.trade_no = [NSString stringWithFormat:@"0001%@%@",locationString,[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"]];
    payReq.billNo = self.trade_no;//商户自定义订单号
    payReq.scheme = @"prefsGuoYangKissLock";//URL Scheme,在Info.plist中配置; 支付宝必有参数
    payReq.billTimeOut = 300;//订单超时时间
    payReq.viewController = self; //银联支付和Sandbox环境必填
    payReq.optional = dict;//商户业务扩展参数，会在webhook回调时返回
    [BeeCloud sendBCReq:payReq];
}

#pragma mark - BCPay回调
- (void)onBeeCloudResp:(BCBaseResp *)resp {
    if(resp.type == BCObjsTypePayResp){
        // 支付请求响应
        BCPayResp *tempResp = (BCPayResp *)resp;
        NSLog(@"paySource:%@",tempResp.paySource);
        if (tempResp.resultCode == 0) {
            NSLog(@"支付情况：%@",resp.resultMsg);
            [KLHttpAPI payoffSuccessWithKeytype:@"1" total_fee:self.money trade_no:self.trade_no completionHandler:^(MKNetworkOperation *operation) {
                NSLog(@"充值返回数据：%@",operation.responseString);
                NSDictionary *dic = operation.responseJSON;
                NSString *isSuccess = [dic objectForKey:@"success"];
                if(isSuccess.integerValue == 1){
                    [[NSUserDefaults standardUserDefaults] setObject:[dic objectForKey:@"msg"] forKey:@"feeaccount"];
                    [self.navigationController popViewControllerAnimated:YES];
                }else{
                    [KLHelp showTextHUDforView:self.view text:@"充值失败"];
                }
            } errorHandler:^(NSString *error) {
                [KLHelp showTextHUDforView:self.view text:@"充值失败"];
            }];
            
            [self hideLoadingMode];
        } else {
            //支付取消或者支付失败
            NSLog(@"支付取消或失败结果信息:resultMsg：%@, errDetail：%@, type：%zd, resultCode：%zd",tempResp.resultMsg,tempResp.errDetail,tempResp.request.type,tempResp.resultCode);
            [self hideLoadingMode];
        }
    }
}

#pragma mark - uitextfield的实时显示方法
-(void)textFieldEditChanged:(TSCurrencyTextField *)textField{
    NSString *text = [textField.text substringFromIndex:1];
    NSArray *array = [text componentsSeparatedByString:@","];
    self.money = [NSMutableString string];
    for (NSString *subStr in array) {
        [self.money appendString:subStr];
    }
    NSLog(@"金额:%.f",self.money.doubleValue * 100);
    if(self.money.doubleValue > 1000 || self.money.doubleValue == 0){
        [self nextBtnNotAllowSelected];
    }else{
        [self nextBtnAllowSelected];
        self.money = [NSMutableString stringWithFormat:@"%.f",self.money.doubleValue * 100];
    }
}

#pragma mark - 下一步按钮可选中状态
-(void)nextBtnAllowSelected{
    [nextBtn setBackgroundColor:RGB_UI_COLOR(8, 128, 181)];
    [nextBtn setEnabled:YES];
}

-(void)nextBtnNotAllowSelected{
    [nextBtn setBackgroundColor:RGB_UI_COLOR(170, 170, 170)];
    [nextBtn setEnabled:NO];
}

#pragma mark - 支付指示器
-(void)showLoadingMode {
    if (!loadingCircle) {
        loadingCircle = [[MZLoadingCircle alloc]initWithNibName:nil bundle:nil];
        loadingCircle.view.backgroundColor = [UIColor clearColor];
        
        //Colors for layers
        loadingCircle.colorCustomLayer = [UIColor colorWithRed:0 green:0.4 blue:0 alpha:1];
        loadingCircle.colorCustomLayer2 = [UIColor colorWithRed:0 green:0.4 blue:0 alpha:0.65];
        loadingCircle.colorCustomLayer3 = [UIColor colorWithRed:0 green:0.4 blue:0 alpha:0.4];
        
        int size = 100;
        
        CGRect frame = loadingCircle.view.frame;
        frame.size.width = size ;
        frame.size.height = size;
        frame.origin.x = self.view.frame.size.width / 2 - frame.size.width / 2;
        frame.origin.y = self.view.frame.size.height / 2 - frame.size.height / 2;
        loadingCircle.view.frame = frame;
        loadingCircle.view.layer.zPosition = MAXFLOAT;
        [self.view addSubview: loadingCircle.view];
        
        [KLHelp blackCoverViewShowAndHide:self.view showOrHide:YES];
    }
}

-(void)hideLoadingMode {
    if (loadingCircle) {
        [loadingCircle.view removeFromSuperview];
        loadingCircle = nil;
        [KLHelp blackCoverViewShowAndHide:self.view showOrHide:NO];
    }
}
@end
